<template>
	<view class="create-activity-container">
		<!-- 活动标题 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>活动标题</view>
				<view class="ai-write-button" @click="handleAIFill">
					<image src="@/static/star.png" />
					<view v-if="!aiFillLoading">一键填写活动内容</view>
					<view v-else style="display: flex; align-items: center"
						>正在思考中...<view class="ml-10"><u-loading-icon mode="semicircle" timing-function="ease" inactive-color="#2b6de5"></u-loading-icon></view
					></view>
				</view>
			</view>
			<u-input v-model="form.title" placeholder="为你的桌游活动起个名字吧" :clearable="false"></u-input>
		</view>
		<AITips :tips="aiFillMap['title']" type="title" @copy="handleCopyTips" @close="handleCloseTips" />
		<!-- 参与人数 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>参与人数</view>
			</view>
			<u-number-box v-model="form.peopNum" :min="2" :max="100"></u-number-box>
		</view>
		<AITips :tips="aiFillMap['peopNum']" type="peopNum" @copy="handleCopyTips" @close="handleCloseTips" />
		<!-- 活动时间 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>活动时间</view>
			</view>
			<view class="location-selector" @click="handleChooseStartTime"
				><u-icon name="clock" size="20"></u-icon>
				<view class="ml-10">开始时间：{{ form.startTime ? displayTime(form.startTime) : '选择开始活动时间' }}</view></view
			>
			<view class="location-selector mt-20" @click="handleChooseEndTime"
				><u-icon name="bell" size="20"></u-icon
				><view class="ml-10"> 结束时间：{{ form.endTime ? displayTime(form.endTime) : '选择开始活动时间' }}</view></view
			>
			<u-datetime-picker
				:show="startTimePicker"
				v-model="form.startTime"
				mode="datetime"
				title="开始时间"
				:minDate="now"
				:maxDate="now + oneDay * 7"
				@confirm="handleConfirmStartTime"
				@cancel="startTimePicker = false"
			></u-datetime-picker>
			<u-datetime-picker
				:show="endTimePicker"
				v-model="form.endTime"
				mode="datetime"
				title="结束时间"
				:minDate="form.startTime"
				:maxDate="form.startTime + oneDay"
				@confirm="endTimePicker = false"
				@cancel="endTimePicker = false"
			></u-datetime-picker>
		</view>
		<!-- 活动地点 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>活动地点</view>
			</view>
			<view class="location-selector" @click="handleChooseLocation"
				><u-icon name="map" size="20"></u-icon><view class="ml-10 text"> {{ form.locationName ? form.locationName : '选择活动地点' }}</view></view
			>
			<map :longitude="form.longitude" :latitude="form.latitude" :markers="markerList" class="map" />
		</view>
		<!-- 选择桌游 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>选择桌游</view>
			</view>
			<scroll-view scroll-x>
				<view class="boardgame-selector" @click="toAddGame">
					<view class="select-button">
						<u-icon name="plus" :color="$themeColor"></u-icon>
						添加桌游
					</view>
					<view v-for="item in playGameList" :key="item.id" class="boardgame-item">
						<image :src="item.picture" />
						<view class="boardgame-name">{{ item.name }}</view>
						<view class="close-icon">
							<u-icon name="close-circle" color="#fff" size="20"></u-icon>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<AITips :tips="aiFillMap['gameList']" type="gameList" @copy="handleCopyTips" @close="handleCloseTips" />
		<!-- 活动描述 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>活动描述</view>
			</view>
			<u-textarea
				v-model="form.content"
				placeholder="请输入活动描述..."
				:clearable="false"
				type="textarea"
				:autoHeight="true"
				:maxlength="300"
				count
			></u-textarea>
		</view>
		<AITips :tips="aiFillMap['content']" type="content" @copy="handleCopyTips" @close="handleCloseTips" />
		<!-- 推荐邀请 -->
		<view class="form-wrapper">
			<view class="form-title">
				<view>推荐邀请</view>
			</view>
			<view class="recommend-invite-wrapper">
				<view v-for="(item, index) in userList" :key="item.id" class="recommend-invite-item">
					<view class="avatar">
						<image :src="item.avatarUrl" />
					</view>
					<view class="invite-info">
						<view class="name">{{ item.nickname }}</view>
						<view class="location">{{ item.city }} {{ item.district }}</view>
					</view>
					<view class="select-button">
						<u-button :color="themeColor" :plain="item.invited" shape="circle" size="small" @click="handleInvite(index)">{{
							item.invited ? '取消' : '邀请'
						}}</u-button>
					</view>
				</view>
			</view>
		</view>
		<!-- 创建活动 -->
		<view class="create-activity-button" @click="handleSubmit">
			<u-button :color="themeColor" shape="circle">创建活动</u-button>
		</view>
	</view>
</template>

<script>
import request from '@/api/http.js';
import AITips from '@/components/AITips/AITips.vue';

export default {
	components: {
		AITips
	},
	data() {
		return {
			form: {
				title: '',
				content: '',
				peopNum: 2,
				longitude: 116.404,
				latitude: 39.915,
				locationName: '',
				address: '',
				startTime: Number(new Date()),
				endTime: Number(new Date()) + 3600 * 1000 * 2 // 比startTime 晚一小时
			},
			markerList: [
				{
					id: 1,
					latitude: 39.915,
					longitude: 116.404,
					iconPath: require('@/static/activity/marker.png'),
					width: 30,
					height: 30
				}
			],
			playGameList: [],
			userList: [],
			startTimePicker: false,
			endTimePicker: false,
			now: Number(new Date()),
			oneDay: 86400000,
			aiFillMap: {
				title: {
					title: 'AI标题建议',
					content: '',
					show: false
				},
				content: {
					title: 'AI内容建议',
					content: '',
					show: false
				},
				peopNum: {
					title: 'AI人数建议',
					content: '',
					show: false
				},
				gameList: {
					title: 'AI建议游玩桌游',
					content: '',
					show: false
				}
			},
			aiFillLoading: false
		};
	},
	mounted() {
		this.getUserLocation();
		this.handleGetUserList();
	},
	methods: {
		receiveData(data) {
			console.log(data);
		},
		toAddGame() {
			uni.navigateTo({
				url: '/pages/Boardgame/AddBoardgame/AddBoardgame'
			});
		},
		async handleGetUserList() {
			const meRes = await request(`/user/getUserData?openid=${uni.getStorageSync('openid')}`);
			const me = meRes.data;
			const res = await request('/user/getUserList');
			this.userList = res.data
				.filter((item) => {
					return item.province == me.province && item.city == me.city && item.openid != me.openid; // 只显示同城用户
				})
				.map((item) => {
					return {
						...item,
						invited: false
					};
				});
		},
		handleChooseLocation() {
			uni.choo;
			uni.chooseLocation({
				success: (res) => {
					this.form.longitude = res.longitude;
					this.form.latitude = res.latitude;
					this.form.locationName = res.name;
					this.form.address = res.address;
					this.markerList = [
						{
							id: 1,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: require('@/static/activity/marker.png'),
							locationName: res.name,
							address: res.address,
							width: 30,
							height: 30
						}
					];
				},
				complete: (error) => {
					console.log(error);
				}
			});
		},
		formatDate(time) {
			let year = new Date(time).getFullYear();
			let month = new Date(time).getMonth() + 1;
			month = month < 10 ? '0' + month : month;
			let day = new Date(time).getDate();
			day = day < 10 ? '0' + day : day;
			let hour = new Date(time).getHours();
			hour = hour < 10 ? '0' + hour : hour;
			let minute = new Date(time).getMinutes();
			minute = minute < 10 ? '0' + minute : minute;
			let second = new Date(time).getSeconds();
			second = second < 10 ? '0' + second : second;
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
		},
		async handleSubmit() {
			let gameId = this.playGameList.map((item) => item.id).join(',');
			const res = await request(
				'/activities/createActivity',
				{
					...this.form,
					gameId: gameId,
					startTime: this.formatDate(this.form.startTime),
					endTime: this.formatDate(this.form.endTime),
					userIds: this.userList.filter((item) => item.invited).map((item) => item.id)
				},
				'POST'
			);
			uni.navigateBack({ delta: 1 });
		},
		handleChooseStartTime() {
			this.startTimePicker = true;
		},
		handleChooseEndTime() {
			this.endTimePicker = true;
		},
		handleConfirmStartTime() {
			this.startTimePicker = false;
			this.$nextTick(() => {
				this.form.endTime = this.form.startTime + 3600 * 1000 * 2;
				this.$forceUpdate();
			});
		},
		displayTime(time) {
			let year = new Date(time).getFullYear();
			let month = new Date(time).getMonth() + 1;
			month = month < 10 ? '0' + month : month;
			let date = new Date(time).getDate();
			date = date < 10 ? '0' + date : date;
			let hour = new Date(time).getHours();
			hour = hour < 10 ? '0' + hour : hour;
			let minute = new Date(time).getMinutes();
			minute = minute < 10 ? '0' + minute : minute;
			return `${year}-${month}-${date} ${hour}:${minute}`;
		},
		async handleAIFill() {
			let gameId = this.playGameList.map((item) => item.id).join(',');
			this.aiFillLoading = true;
			const res = await request(
				'/activities/aiFill',
				{
					...this.form,
					gameId: gameId,
					startTime: this.formatDate(this.form.startTime),
					endTime: this.formatDate(this.form.endTime)
				},
				'POST'
			);
			this.aiFillLoading = false;
			const aiFill = res.data.data;
			let aiFillMap = {};
			if (aiFill.title) {
				aiFillMap.title = {
					title: 'AI标题建议',
					content: aiFill.title,
					show: true
				};
			}
			if (aiFill.content) {
				aiFillMap.content = {
					title: 'AI内容建议',
					content: aiFill.content,
					show: true
				};
			}
			if (aiFill.peopNum) {
				aiFillMap.peopNum = {
					title: 'AI人数建议',
					content: `建议人数为${aiFill.peopNum}人，因为您的活动桌游最少需要${aiFill.peopNum}人`,
					number: aiFill.peopNum,
					show: true
				};
			}
			if (aiFill.gameList) {
				aiFillMap.gameList = {
					title: 'AI建议游玩桌游',
					content: aiFill.gameList.map((item) => item.name).join('、'),
					games: aiFill.gameList,
					show: true
				};
			}
			this.aiFillMap = aiFillMap;
		},
		handleCopyTips(type) {
			if (type === 'title') {
				this.form.title = this.aiFillMap[type].content;
			} else if (type === 'content') {
				this.form.content = this.aiFillMap[type].content;
			} else if (type === 'peopNum') {
				this.form.peopNum = this.aiFillMap[type].number;
			} else if (type === 'gameList') {
				this.playGameList = [...this.playGameList, ...this.aiFillMap[type].games];
			}
		},
		handleCloseTips(type) {
			this.aiFillMap[type].show = false;
		},
		async getUserLocation() {
			uni.getFuzzyLocation({
				success: (res) => {
					console.log(res);
					this.markerList = [
						{
							id: 1,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: require('@/static/activity/marker.png'),
							width: 30,
							height: 30
						}
					];
					this.form.latitude = res.latitude;
					this.form.longitude = res.longitude;
				},
				fail: (err) => {
					console.log(err);
				}
			});
		},
		handleInvite(index) {
			this.userList[index].invited = !this.userList[index].invited;
		}
	}
};
</script>

<style lang="scss">
.create-activity-container {
	padding: 20rpx;
	.form-wrapper {
		padding: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		.form-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 32rpx;

			.ai-write-button {
				display: flex;
				align-items: center;
				gap: 10rpx;
				font-size: $font-size-base;
				color: $theme-color;
				image {
					width: 40rpx;
					height: 40rpx;
				}

				&:active {
					opacity: 0.8;
				}
			}
		}

		.u-input {
			padding: 20rpx 40rpx !important;
		}

		.u-number-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			border: 1px solid #ccc;
			border-radius: 10rpx;
			padding: 20rpx !important;

			input {
				background-color: #fff !important;
				width: 100%;
			}

			.u-number-box__minus,
			.u-number-box__plus {
				width: 60rpx;
				height: 60rpx;
				border-radius: 10rpx;
				background-color: $theme-color;
				color: #fff;
				font-size: 32rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.u-number-box__minus--disabled,
			.u-number-box__plus--disabled {
				background-color: #ccc;
				color: #999;
			}
		}

		.u-textarea {
			padding: 20rpx !important;
			min-height: 200rpx;
		}

		.location-selector {
			display: flex;
			align-items: center;
			border: 1px solid #ccc;
			border-radius: 10rpx;
			padding: 25rpx 40rpx;
			gap: 10rpx;
			color: #333;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;

			.text {
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		map {
			width: 100%;
			height: 300rpx;
			margin-top: 20rpx;
			border-radius: 10rpx;
		}

		.boardgame-selector {
			display: flex;
			flex-direction: row;
			overflow-x: scroll;
			align-items: center;
			gap: 20rpx;
			width: max-content;
			padding: 20rpx 0;

			.select-button {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				background-color: #fff9f4;
				gap: 20rpx;
				border: 1px dashed $theme-color;
				width: 200rpx;
				height: 280rpx;
				color: $theme-color;
				font-size: $font-size-base;
				border-radius: 25rpx;
				padding: 20rpx;
				box-shadow: 0 3px 6px #ccc;
			}

			.boardgame-item {
				width: 240rpx;
				height: 320rpx;
				border-radius: 25rpx;
				overflow: hidden;
				position: relative;

				image {
					width: 100%;
					height: 100%;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.6) 100%);
					}
				}

				.boardgame-name {
					font-size: $font-size-base;
					color: #fff;
					position: absolute;
					bottom: 20rpx;
					left: 20rpx;
					z-index: 10;
				}

				.close-icon {
					position: absolute;
					top: 20rpx;
					right: 20rpx;
					z-index: 11;
				}
			}
		}

		.recommend-invite-wrapper {
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			.recommend-invite-item {
				display: flex;
				align-items: center;
				gap: 10rpx;

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					overflow: hidden;
					image {
						width: 100%;
						height: 100%;
					}
				}

				.invite-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.name {
						font-size: 32rpx;
						font-weight: bold;
					}

					.location {
						font-size: $font-size-small;
						color: #999;
					}
				}

				.select-button {
					width: 100rpx;
				}
			}
		}
	}

	.create-activity-button {
		display: flex;
		justify-content: center;
		margin-top: 50rpx;
	}
}
</style>
